package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

func main() {
	//test()
	//test1()
	//test2()
	test3()
}

//一行一行读取文件内容
func test() {
	inputFile, inputError := os.Open("/opt/wwwroot/go-learn/go_learn/test.txt")
	if inputError != nil {
		fmt.Printf("An error occurred on opening the inputfile\n" +
			"Does the file exist?\n" +
			"Have you got acces to it?\n")
		return // exit the function on error
	}
	defer inputFile.Close()

	inputReader := bufio.NewReader(inputFile)
	for {
		inputString, readerError := inputReader.ReadString('\n')
		fmt.Printf("The input was: %s", inputString)
		if readerError == io.EOF {
			return
		}
	}
}

//一次性读取所有文件内容
func test1() {
	inputFile := "/opt/wwwroot/go-learn/go_learn/test.txt"
	//outputFile := "products_copy.txt"
	buf, err := ioutil.ReadFile(inputFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
		// panic(err.Error())
	}
	fmt.Printf("%s\n", string(buf))
	//err = ioutil.WriteFile(outputFile, buf, 0644) // oct, not hex
	//if err != nil {
	//	panic(err.Error())
	//}
}

//完全覆盖写入文件,使用缓冲区
func test2() {
	// var outputWriter *bufio.Writer
	// var outputFile *os.File
	// var outputError os.Error
	// var outputString string
	outputFile, outputError := os.OpenFile("test2_copy.txt", os.O_WRONLY|os.O_CREATE, 0666)
	if outputError != nil {
		fmt.Printf("An error occurred with file opening or creation\n")
		return
	}
	defer outputFile.Close()

	outputWriter := bufio.NewWriter(outputFile)
	outputString := "hello world!\n"

	for i := 0; i < 10; i++ {
		_, err := outputWriter.WriteString(outputString)
		if err != nil {
			fmt.Println(err)
			return
		}
	}
	outputWriter.Flush()

	fmt.Println("end")
}

//完全覆盖写入文件，不使用缓冲区
func test3() {
	os.Stdout.WriteString("hello, world\n")
	f, _ := os.OpenFile("test.txt", os.O_CREATE|os.O_WRONLY, 0666)
	defer f.Close()
	f.WriteString("hello, world in a file\n")
}
